<!-- eslint-disable vue/valid-v-slot -->
<!-- eslint-disable vue/no-lone-template -->
<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="seachForm" :model="form">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="name" hide-label>
                    <a-input
                      v-model="form.name"
                      class="width100"
                      placeholder="请输入渠道名称"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="coding" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.coding"
                      placeholder="请选择渠道系统"
                      allow-clear
                      allow-search
                    >
                      <a-option
                        v-for="item in treeData.list"
                        :key="item.name"
                        :value="item.coding"
                        >{{ item.name }}</a-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="btns" hide-label>
                    <a-space :size="15">
                      <a-button
                        type="primary"
                        v-permission="channelList"
                        html-type="submit"
                        @click="doRefresh(1)"
                        ><template #icon> <icon-search /> </template>搜索</a-button
                      >
                      <a-button v-permission="channelList" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button
            v-permission="'/app/mall/channel/add'"
            type="primary"
            @click="onAddItem"
            @contextmenu.prevent.stop=";(modal.visibles = true), (addTitles = '新建渠道')"
          >
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>新建</template>
          </a-button>
          <a-button
            v-permission="exportChannelList"
            type="outline"
            @click="exportChannelLists"
            :loading="loading"
          >
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>导出</template>
          </a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :bordered="{ wrapper: true, cell: tables.bordered }"
          :stripe="(tables.striped as boolean)"
          :loading="tables.tableLoading"
          :data="table.dataList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          :columns="tableColumns.list"
          table-layout-fixed
          :show-empty-tree="false"
          :hide-expand-button-on-empty="true"
          :default-expand-all-rows="false"
          :isLeaf="false"
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              :align="item.align"
              :title="(item.title as string)"
              :width="item.width"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
              :ellipsis="true"
              :tooltip="true"
            >
              <template v-if="item.key === 'cardStatistics'" #cell="{ record }">
                <a-space>
                  {{ record.cardStatistics.total }}
                </a-space>
              </template>
              <template v-if="item.key === 'orderSubmit'" #cell="{ record }">
                <a-space>
                  <a-tag v-if="record.orderSubmit" color="arcoblue">开启</a-tag>
                  <a-tag v-else color="red">关闭</a-tag>
                </a-space>
              </template>
              <template v-if="item.key === 'nextSubmit'" #cell="{ record }">
                <a-space>
                  <a-tag v-if="record.nextSubmit" color="arcoblue">开启</a-tag>
                  <a-tag v-else color="red">关闭</a-tag>
                </a-space>
              </template>
              <template v-if="item.key === 'polling'" #cell="{ record }">
                <a-space>
                  <a-tag v-if="record.polling" color="arcoblue">开启</a-tag>
                  <a-tag v-else color="red">关闭</a-tag>
                </a-space>
              </template>
              <template v-if="item.key === 'actions'" #cell="{ record }">
                <a-space style="display: flex; flex-wrap: wrap">
                  <a-button
                    size="small"
                    type="text"
                    class="butten"
                    v-permission="'/app/mall/channel/update'"
                    @click="infoDepartments(record)"
                  >
                    编辑
                  </a-button>
                  <a-button
                    size="small"
                    v-permission="'/app/mall/channel/add'"
                    class="butten"
                    type="text"
                    @click="copy(record)"
                  >
                    复制
                  </a-button>
                  <a-button
                    size="small"
                    v-permission="'/app/mall/channel/del'"
                    class="butten"
                    type="text"
                    @click="onDeleteItem(record)"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
      <template #footer>
        <TableFooter ref="tableFooterRef" :pagination="pagination" />
      </template>
    </TableBody>
    <a-modal
      v-model:visible="modal.visible"
      width="600px"
      :mask-closable="false"
      @before-close="beforeClose"
      title-align="start"
    >
      <template #title> {{ addTitles }} </template>
      <div>
        <a-form ref="infoRef" :labelCol="{ span: 12 }" :model="info.info" :auto-label-width="true">
          <a-form-item
            label="渠道系统"
            field="coding"
            :rules="[{ required: true, message: '请选择渠道系统' }]"
            asterisk-position="end"
            :validate-trigger="['change']"
          >
            <a-select
              placeholder="请选择渠道系统"
              v-model="info.info.coding"
              allow-search
              @change="encodingFn"
            >
              <a-option v-for="item in treeData.list" :key="item.name" :value="item.coding">{{
                item.name
              }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="渠道名称"
            field="name"
            :rules="[
              { required: true, message: '请输入渠道名称' },
              { minLength: 1, maxLength: 30, message: '长度在 1 - 20个字符' },
            ]"
            asterisk-position="end"
          >
            <a-input placeholder="请输入渠道名称" v-model.trim="info.info.name" />
          </a-form-item>
          <a-form-item label="备注" field="remarks" style="width: 100%">
            <a-textarea placeholder="请输入备注" v-model.trim="info.info.remarks" allow-clear />
          </a-form-item>
          <a-divider v-if="info.info.params.length > 0" dashed style="margin-bottom: 25px"
            >对接参数</a-divider
          >
          <a-form-item
            v-for="item in info.info.params"
            :key="item.key"
            :label="item.name"
            :field="item.key"
          >
            <a-input :placeholder="`请输入${item.name}`" v-model.trim="item.value" />
          </a-form-item>
          <!-- <a-form-item label="接口地址" field="url" :rules="rulesssssssss">
            <a-input placeholder="请输入接口地址" v-model.trim="info.info.url" />
          </a-form-item> -->
        </a-form>
      </div>
      <template #footer>
        <a-space v-if="info.info.id">
          <a-button @click="beforeClose">取消</a-button>
          <a-button type="primary" @click="handleSubmit">确定</a-button>
        </a-space>
        <div v-else style="display: flex; justify-content: space-between; width: 100%">
          <a-checkbox v-model="checked1">继续新建下一个渠道</a-checkbox>
          <a-space>
            <a-button @click="beforeClose">取消</a-button>
            <a-button type="primary" @click="handleSubmit">确定</a-button>
          </a-space>
        </div>
      </template>
    </a-modal>
    <!-- 复制渠道 -->
    <a-modal
      v-model:visible="copyVisible"
      title="复制渠道"
      width="600px"
      @before-close="copyCel"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="copyRef" :auto-label-width="true" :model="copyForm">
        <a-form-item field="name" label="渠道名称">
          {{ copyForm.name }}
        </a-form-item>
        <a-form-item field="copyType" label="复制类型">
          <a-radio-group class="radio-bcg" v-model="copyForm.copyType">
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">一键复制</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">编辑并复制</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="copyForm.copyType == true"
          field="copyNum"
          label="复制数量"
          :rules="[{ required: true, message: '复制数量不能为空' }]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input-number
            v-model="copyForm.copyNum"
            :min="1"
            placeholder="请输入复制数量"
            allow-clear
          />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="copyCel">取消</a-button>
          <a-button type="primary" @click="copyCancel">确定</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { channelList, exportChannelList, verificationChannel } from '@/api/url'
  import useCommonStore from '@/store/modules/common'
  import { post, get } from '@/api/http'
  import { usePagination, useRowKey, useTable } from '@/hooks/table'
  import { onMounted, reactive, ref } from 'vue'

  import _ from 'lodash-es'

  import { Message, Modal } from '@arco-design/web-vue'
  const useCommon = useCommonStore()

  const table = useTable()

  const pagination = usePagination(doRefresh)

  const infoRef = ref()

  const copyRef = ref()

  const copyNum = ref(0)
  const show = ref(false)
  const list: any = ref([])

  const copyVisible = ref(false)
  const checked1 = ref(false)

  const addTitles = ref('新建渠道')

  const copyForm = ref({
    id: '',
    name: '',
    copyType: true,
    copyNum: 1,
  })

  const loading = ref(false)

  const seachForm = ref()

  const modal = reactive({
    visible: false,
    key: '1',
    visibles: false,
  })

  const form = reactive({
    name: '', //渠道名称
    coding: '',
  })

  const tables = reactive({
    tableLoading: false,
    bordered: false,
    striped: false,
    expand: [1],
    isExpand: false,
  })

  const info: any = reactive({
    info: {
      name: '',
      coding: '', //渠道编码
      remarks: '',
      params: [],
    },
    disabled: false,
  })

  const treeData = reactive({
    list: [{ coding: 'YINGMENG', name: '迎梦', url: 'http://www.yingmengyun.com' }],
    parentId: [],
    option: {},
  })

  const tableColumns: any = reactive({
    list: [
      {
        title: '渠道ID',
        key: 'id',
        dataIndex: 'id',
        align: 'left',
        checked: true,
        width: 100,
      },
      {
        title: '渠道名称',
        key: 'name',
        dataIndex: 'name',
        align: 'left',
        checked: true,
        width: 220,
      },
      {
        title: '渠道系统',
        key: 'codingName',
        dataIndex: 'codingName',
        align: 'left',
        checked: true,
        width: 220,
      },
      {
        title: '设备数量',
        key: 'num',
        dataIndex: 'num',
        align: 'left',
        checked: true,
        width: 200,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        align: 'left',
        checked: true,
        width: 190,
      },
      {
        title: '操作',
        key: 'actions',
        dataIndex: 'actions',
        align: 'left',
        checked: true,
        width: 220,
        fixed: 'right',
      },
    ],
  })

  const rowKey = useRowKey('id')

  const encodingFn = (val: any) => {
    info.info.params = []
    if (val === 'SELFSUPPORT') {
      info.info.polling = false
      info.info.productStatus = false
    }
    treeData.list.forEach((item: any) => {
      if (item.coding == val) {
        info.info.params = item.params
      }
    })
  }

  const resetSeach = () => {
    seachForm.value.resetFields()
    doRefresh(1)
  }

  const exportChannelLists = () => {
    loading.value = true
    useCommon
      .downLoads('/app/device/channel/export', form, '设备渠道列表')
      .then(() => {
        loading.value = false
      })
      .catch(() => {
        loading.value = false
      })
  }

  const copy = (val: any) => {
    info.info = JSON.parse(JSON.stringify(val))
    copyForm.value.name = val.name
    info.info.id = ''
    copyVisible.value = true
  }

  const towCss = (val: any) => {
    info.info = JSON.parse(JSON.stringify(val))
    if (info.info.childrenData) {
      show.value = true
      list.value = val.childrenData
    }
    addTitles.value = '编辑渠道'
    modal.visibles = true
  }

  const copyCel = () => {
    copyRef.value.resetFields()
    copyVisible.value = false
  }

  const copyCancel = () => {
    copyRef.value.validate((error: any) => {
      if (!error) {
        if (copyForm.value.copyType == true) {
          const num = copyForm.value.copyNum
          for (let index = 0; index < num; index++) {
            addChannels()
          }
          copyRef.value.resetFields()
        } else {
          info.info.id = ''
          copyNum.value = 1
          copyRef.value.resetFields()
          copyVisible.value = false
          modal.visible = true
        }
      }
    })
  }

  const beforeClose = () => {
    infoRef.value.clearValidate()
    infoRef.value.resetFields()
    treeData.parentId = []
    checked1.value = false
    info.info.id = ''
    info.info.params = []
    modal.visible = false
    modal.visibles = false
  }

  const handleSubmit = () => {
    infoRef.value.validate((error: any) => {
      if (!error) {
        if (info.info.id) {
          updateChannels()
        } else {
          addChannels()
        }
      } else {
        console.log(error)
      }
    })
  }

  const infoDepartments = (val: any) => {
    addTitles.value = '编辑渠道'
    info.info = JSON.parse(JSON.stringify(val))
    modal.visible = true
  }

  const updateChannels = () => {
    post({
      url: '/app/device/channel/update',
      data: {
        ...info.info,
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        beforeClose()
        doRefresh()
      }
    })
  }

  const addChannels = () => {
    post({
      url: '/app/device/channel/add',
      data: {
        ...info.info,
      },
    }).then((res) => {
      if (res.code == 0) {
        if (checked1.value == true) {
          infoRef.value.clearValidate()
          infoRef.value.resetFields()
          treeData.parentId = []
          checked1.value = false
          info.info.id = ''
          info.info.params = []
          Message.success('新建成功，当前已开始新建新的渠道')
          doRefresh()
        } else {
          Message.success(res.msg)
          copyCel()
          beforeClose()
          doRefresh()
        }
      }
    })
  }

  const encodingLists = () => {
    get({
      url: '/app/device/channel/coding/values',
      data: () => {
        return {}
      },
    }).then((res) => {
      treeData.list = res.data
      return res.data
    })
  }

  function onUpdateBorder(isBordered: boolean) {
    tables.bordered = isBordered
  }

  function onUpdateStriped(isStriped: boolean) {
    tables.striped = isStriped
  }

  function doRefresh(value?: number) {
    tables.tableLoading = true
    if (value) {
      pagination.page = value
    }
    get({
      url: '/app/device/channel/page',
      data: {
        ...form,
        page: pagination.page,
        size: pagination.pageSize,
      },
    }).then((res) => {
      tables.tableLoading = false
      encodingLists()
      // res.data.list.forEach((item: any) => {
      //   item.childrenData = item.children
      //   delete item.children
      // })
      table.handleSuccess(res.data.list)
      pagination.setTotalSize((res.data as any).totalSize)
      return res.data.list
    })
  }

  //删除渠道
  const deleteChannels = (val: number) => {
    get({
      url: '/app/device/channel/del',
      data: {
        id: val,
      },
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        doRefresh()
      }
    })
  }

  const onDeleteItem = (item: any) => {
    Modal.warning({
      title: '操作确认',
      content: '确定要删除此渠道？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '确定',
      onOk() {
        deleteChannels(item.id)
      },
    })
  }

  function onAddItem() {
    info.info.id = ''
    info.info.parameters = []
    info.info.otherParameters = null
    addTitles.value = '新建渠道'
    modal.visible = true
  }

  // //跟踪API开始时间限制结束时间
  // function changeTraceEnd(time: any) {
  //   return time.getTime() > new Date(form.endTime).getTime() //大于结束时间的不选
  // }
  // //跟踪API结束时间限制开始时间
  // function changeTraceStart(time: any) {
  //   return time.getTime() < new Date(form.addTime).getTime() //小于开始时间的不选
  // }

  onMounted(async () => {
    await doRefresh()
  })
</script>

<style lang="less" scoped>
  .tagList {
    margin-top: 20px;
    width: 250px;
    border-radius: 5px;
    max-height: 670px;
    border: 1px solid #f5f5f5;
    display: flex;
    flex-wrap: wrap;
    align-content: space-between;
    overflow: hidden;

    .tagTops {
      width: 100%;

      .activeTag {
        width: 100%;
        height: 36px;
        text-align: center;

        .actives {
          display: block;
          cursor: pointer;
          width: 100%;
          height: 100%;
          line-height: 34px;
          color: #fff;
          background-color: rgb(var(--primary-6));
        }

        .wraps {
          cursor: pointer;
          padding: 0px 20px;
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          line-height: 14px;

          img {
            width: 15px;
            height: 15px;
            margin-right: 10px;
          }
        }

        .noactive {
          display: block;
          cursor: pointer;
          width: 100%;
          color: rgb(var(--gray-10));
          height: 100%;
          line-height: 14px;
        }
      }
    }

    .tagBottoms {
      width: 100%;
      padding: 0px 20px 20px;

      :deep(.arco-btn-outline) {
        width: 100%;
      }
    }
  }
  .dockingBox {
    width: 100%;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    .dockingLeft {
      width: 290px;
      padding: 20px;
      border-radius: 5px;
      border: 1px solid #f5f5f5;
      box-sizing: border-box;
      margin-right: 20px;
    }
    .dockingRight {
      width: 100%;
      border-radius: 5px;
      padding: 20px;
      max-height: 670px;
      border: 1px solid #f5f5f5;
      box-sizing: border-box;
      scrollbar-width: thin; /* 细滚动条 */
    }

    .dockingRights {
      width: 100%;
      border-radius: 5px;
      padding: 20px;
      max-height: 670px;
      border: 1px solid #f5f5f5;
      box-sizing: border-box;
      scrollbar-width: thin; /* 细滚动条 */
      :deep(.arco-scrollbar .arco-scrollbar-type-track) {
        padding-bottom: 0 !important;
      }
    }
  }

  .yin {
    box-shadow: 0px 10px 10px -8px #0000001a inset;
  }
  .yin1 {
    box-shadow: 0px -10px 10px -8px #0000001a inset;
  }
  .main-container {
  }
  :deep(.arco-table-td-content button) {
    padding: 0px !important;
    margin-right: 8px;
    background: none !important;
  }
  // :deep(.arco-form-item-label) {
  //   width: 68px;
  //   text-align: right;
  // }
  :deep(.arco-table-cell-expand-icon) {
    justify-content: center;
  }

  :deep(.arco-tabs-tab-title) {
    width: 52px !important;
    text-align: center;
  }

  :deep(.arco-tabs-nav-type-capsule .arco-tabs-nav-tab-list) {
    padding: 12px 12px;
  }
  .tabs {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 40px;
    margin-bottom: 20px;

    .button {
      box-sizing: border-box;
      padding-bottom: 5px;
    }
  }

  .action {
    color: #009dff;
    border-bottom: 3px solid #009dff;
  }

  .butten {
    margin-right: 5px;
    padding: 0px;
  }

  .input516 {
    width: 470px;
    margin-left: 20px;
  }
  :deep(.arco-divider-horizontal) {
    margin: 7px 0;
  }
  :deep(.arco-divider-text) {
    top: 0;
    line-height: 1;
  }
  /* :deep(.scrollBox) {
    padding-bottom: 0px !important;
  } */
</style>
<style>
  .arco-drawer-body {
    padding: 0 !important;
  }
</style>
